using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Systems.Security;
using Deepcode.Flux.Core.Services.State;
using Deepcode.Flux.Core.Extensions;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Users_ui_FormFormsEdit : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxSecUsers"; } }
	#endregion
	#region ViewState storage
	/// <summary>
	/// Stores the state of the listing view
	/// </summary>
	public string ListingState
	{
		get
		{
			return (string)ViewState["ListingState"];
		}
		set
		{
			ViewState["ListingState"] = value;
		}
	}
	/// <summary>
	/// Stores the ID of the record being edited
	/// </summary>
	public int RecordID
	{
		get
		{
			object o = ViewState["RecordID"];
			if (o == null) return -1;
			return (int)o;
		}
		set
		{
			ViewState["RecordID"] = value;
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Tell Email RE validator to use the email regex
			EmailRE.ValidationExpression = Deepcode.Flux.Core.Services.Assistant.Validations.EmailValidationExpression;

			// Store any state information from the calling listing
			this.ListingState = GetAttribute("state", "");
			this.RecordID = GetAttribute("ID", -1);

			// Load the record specified
			AdministrationUsers users = new AdministrationUsers();
			AdministrationUser user = users.GetUserByID(this.RecordID);
			if (user == null) GoBack();

			// Load the user details
			RealName.Text = user.RealName;
			EmailAddress.Text = user.EMailAddress;
			IsSuperUser.Checked = user.IsSuperUser;

			// Setup the UI. 
			PopulateGroups();

			// Only other supers can set super flag
			if (!Deepcode.Flux.Core.Services.Security.AdministrationSecurity.IsSuperUser())
				extendedProperties.Visible = false;
		}
	}
	#endregion
	#region Page Init
	/// <summary>
	/// Initialisation - hook up events etc
	/// </summary>
	/// <param name="e"></param>
	protected override void OnInit(EventArgs e)
	{
		base.OnInit(e);
		EmailExists.ServerValidate += new ServerValidateEventHandler(ValidateEmailExists);
	}
	#endregion
	#region Navigation
	/// <summary>
	/// Returns to the listing, restoring state
	/// </summary>
	protected void GoBack()
	{
		string url = String.Format("listForms.aspx?state={0}", this.ListingState);
		Response.Redirect(url, true);
	}
	#endregion
	#region Save/Cancel handlers
	/// <summary>
	/// User cancelled the save, go back to previous page
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnCancel_Click(object sender, EventArgs e)
	{
		GoBack();
	}
	/// <summary>
	/// User clicked the save button, store the data
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnSave_Click(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;
		AdministrationUsers users = new AdministrationUsers();
		AdministrationUser u = users.GetUserByID(this.RecordID);
		if (u == null) GoBack();

		u.EMailAddress = this.EmailAddress.Text;
		u.RealName = this.RealName.Text;
		u.IsSuperUser = this.IsSuperUser.Checked;
		users.Save(u);

		int[] selectedIDs = Deepcode.Flux.Core.Services.Assistant.ControlUtil.GetListSelectedInts(this.UserGroups.Items);
		users.SetGroups(u.PK_ID, selectedIDs);

		QuickAudit.RaiseInformation(
			new AuditUser(),
			"Flux", "User manager",
			"modified user {0} ({1} {2})",
			u.PK_ID, u.RealName, u.EMailAddress);
	
		
		GoBack();
	}
	#endregion
	#region Data functions for groups checklists
	/// <summary>
	/// Loads the groups checkbox list
	/// </summary>
	private void PopulateGroups()
	{
		AdministrationGroups GroupManager = new AdministrationGroups();
		AdministrationGroup[] usersgroups = GroupManager.GetGroupsForUser(this.RecordID);
		AdministrationGroup[] groups = GroupManager.GetAllGroups();
		foreach (AdministrationGroup group in groups)
		{
			ListItem item = new ListItem();
			item.Value = group.PK_ID.ToString();
			item.Text = group.GroupName;
			foreach (AdministrationGroup g in usersgroups)
				if (g.PK_ID == group.PK_ID)
				{
					item.Selected = true;
					break;
				}

			this.UserGroups.Items.Add(item);
		}
	}
	#endregion
	#region Custom validators
	/// <summary>
	/// Checks to ensure the email address isn't already registered
	/// </summary>
	/// <param name="source"></param>
	/// <param name="args"></param>
	private void ValidateEmailExists(object source, ServerValidateEventArgs args)
	{
		AdministrationUsers users = new AdministrationUsers();
		AdministrationUser u = users.GetUserByEmail(args.Value);
		if ((u != null) && (u.PK_ID != this.RecordID)) args.IsValid = false;
		else args.IsValid = true;
	}
	#endregion
}
